package com.exercise.ThreadSynchronization.SynchronizedCode;

public class SyncStaticMethodCounter {
    private static int count = 0;

    // 同步静态方法，锁对象是 SyncStaticMethodCounter.class
    public static synchronized void increment() {
        count++;
        System.out.println("Count: " + count + " by " + Thread.currentThread().getName());
    }

    public static int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        // 定义任务：每个线程调用 1000 次 increment
        Runnable task = ()->{
            for (int i = 0; i < 1000; i++) {
                SyncStaticMethodCounter.increment();
            }
        };
        // 创建两个线程
        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");

        //启动线程
        thread1.start();
        thread2.start();

        // 等待线程结束
        thread1.join();
        thread2.join();

        // 输出最终计数
        System.out.println("Final count: " + SyncStaticMethodCounter.getCount()); // 预期输出：2000
    }

}
